package com.lianzhihui.romeex.ui.account;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.donkingliang.labels.LabelsView;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lianzhihui.romeex.adapter.WordsItemAdapter;
import com.lianzhihui.romeex.bean.user.CountryCode;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.config.DataManager;
import com.lianzhihui.romeex.database.DataBaseManager;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.mvp.presenter.SyncUserPresenter;
import com.lianzhihui.romeex.mvp.view.SyncUserView;
import com.lianzhihui.romeex.ui.MainActivity;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.utils.DensityUtil;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.AESCrypt;
import com.lianzhihui.romeex.utils.JS2AndroidUtil;
import com.lianzhihui.romeex.utils.RecyclerItemDecoration;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.mvp.view.LoginView;


import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ProjectName: NBN
 * @ClassName: VerifyMnemonicWordActivity
 * @Description: 验证助记词
 * @Author: echo
 * @CreateDate: 2019/10/24 13:46
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/10/24 13:46
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class VerifyMnemonicWordActivity extends BaseActivity implements LoginView, LabelsView.OnLabelClickListener, SyncUserView {

    @BindView(R.id.tv_cache_selected_words)
    TextView tv_cache_selected_words;
    @BindView(R.id.tv_error)
    TextView tv_error;
    @BindView(R.id.mBridgeWebView)
    BridgeWebView mBridgeWebView;
    @BindView(R.id.labelsView)
    LabelsView labelsView;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private WalletInfo walletInfo;
    private List<String> wardsOriginal;
    private JS2AndroidUtil jS2AndroidUtil;
    private boolean isManage;
    private SyncUserPresenter syncUserPresenter;
    private WordsItemAdapter wordsItemAdapter;
    private ArrayList<String> wordsItemList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_verify_mnemonic_word;
    }

    @Override
    protected void initView() {
        setTitle(getResources().getString(R.string.toolbar_verify_help_word));
        isManage = getIntent().getBooleanExtra("isManage", false);
        walletInfo = (WalletInfo) getIntent().getSerializableExtra("walletInfo");
        LogUtil.error("ramon", "vm keystore: " + walletInfo.getCiphertext());
        syncUserPresenter = new SyncUserPresenter(this, this);
        jS2AndroidUtil = new JS2AndroidUtil(this, this);
        mBridgeWebView.addJavascriptInterface(jS2AndroidUtil, "Android");
        mBridgeWebView.setDefaultHandler(new DefaultHandler());
        mBridgeWebView.loadUrl("file:///android_asset/index.html");
        mBridgeWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {

                }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
//        RecyclerItemDecoration decoration = new RecyclerItemDecoration(DensityUtil.dip2px(this,16), 3);
        RecyclerItemDecoration decoration = new RecyclerItemDecoration(0, 3);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        wordsItemAdapter = new WordsItemAdapter(new ArrayList<>());
        mRecyclerView.setAdapter(wordsItemAdapter);
        splitWords();
    }

    @Override
    protected void initData() {

    }

    HashMap<Integer, String> cacheSelectedMap = new HashMap<>();
    List<Integer> cacheSelectedList = new ArrayList<>();
    String lastWords = "";

    private void splitWords() {
        wardsOriginal = Arrays.asList(walletInfo.getMnemonicWords().split(" "));
        List<String> labels = Arrays.asList(walletInfo.getMnemonicWords().split(" "));
        Collections.shuffle(labels);
        labelsView.setLabels(labels);
        labelsView.setOnLabelClickListener(this);
        wordsItemList = new ArrayList<>();
        for (int i = 0; i < labels.size(); i++) {
            wordsItemList.add("");
        }
        wordsItemAdapter.setNewData(wordsItemList);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onLabelClick(TextView label, Object data, int position) {
        tv_error.setVisibility(View.INVISIBLE);
        if (cacheSelectedMap.size() == 0) {//第一次进
            cacheSelectedMap.put(position, data.toString());
            cacheSelectedList.add(position);
            lastWords = data.toString();
            appendSelectedText(cacheSelectedMap);
//            label.setTextColor(getResources().getColor(R.color.white));
            return;
        }
        if (TextUtils.isEmpty(cacheSelectedMap.get(position))) {//如果不包含已选择的
            cacheSelectedMap.put(position, data.toString());
            cacheSelectedList.add(position);
            lastWords = data.toString();
            appendSelectedText(cacheSelectedMap);
//            label.setTextColor(getResources().getColor(R.color.white));
        } else {//如果包含
            if (data.toString().equals(getLastPosationWords())) {//如果包含的是最后一项--删除
                cacheSelectedMap.remove(position);
                removeLabes();
                appendSelectedText(cacheSelectedMap);
//                label.setTextColor(getResources().getColor(R.color.text333));
            }
        }
        Log.d("splitWords-pos:", position + "");
    }

    private void removeLabes() {
        int lastIndex = cacheSelectedList.size() - 1;
        cacheSelectedList.remove(lastIndex);
    }

    public String getLastPosationWords() {
        int lastIndex = labelsView.getSelectLabelDatas().size() - 1;
        String word = labelsView.getSelectLabelDatas().get(lastIndex).toString();
        return word;
    }

    public void appendSelectedText(HashMap<Integer, String> cacheSelected) {
        StringBuffer stringBuffer = new StringBuffer();
        labelsView.setSelects(cacheSelectedList);
        List<String> values = labelsView.getSelectLabelDatas();
        for (int i = 0; i < values.size(); i++) {
            stringBuffer.append(" " + values.get(i));
        }
        String stringText = stringBuffer.toString().trim();
        tv_cache_selected_words.setText(stringText);
        doNewArrays(stringText);
    }

    private void doNewArrays(String str) {
        String[] stringArray = str.split(" ");
        for (int i = 0; i < wordsItemList.size(); i++) {
            wordsItemList.set(i, "");
        }
        for (int i = 0; i < stringArray.length; i++) {
            wordsItemList.set(i, stringArray[i]);
        }
        wordsItemAdapter.setNewData(wordsItemList);
    }

    /**
     * 验证方法
     */
    public void verifyState() {
        //todo 无需输入验证
//        showLoading("");
//        importWallet(walletInfo.getMnemonicWords());
        if (wardsOriginal.size() == labelsView.getSelectLabels().size()) {//此步骤确认是否选择完
            String words = tv_cache_selected_words.getText().toString().trim();
            if (walletInfo.getMnemonicWords().equals(words)) {//此步骤确认是否存在错误
                //通过验证
                Log.e("ramon", "通过验证");
//                importWallet(words);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLoading("");
                        importWallet(walletInfo.getMnemonicWords());
                    }
                });

            } else {
//                Toast.makeText(mActivity, getString(R.string.nbn_input_words_error), Toast.LENGTH_SHORT).show();
                tv_error.setVisibility(View.VISIBLE);
            }
        } else {
//            Toast.makeText(mActivity, getString(R.string.nbn_input_complate_words), Toast.LENGTH_SHORT).show();
            tv_error.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 导入钱包
     *
     * @param words
     */
    public void importWallet(String words) {
        showLoading(getResources().getString(R.string.loading_import_wallet));
        jS2AndroidUtil.setWalletType(2);
        String jsFunction = "javascript:importWallet('" + words + "')";
        mBridgeWebView.evaluateJavascript(jsFunction, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String data) {
                dismissLoading();
            }
        });
//        LogUtil.error("ramon",walletInfo.toString());
//        DataBaseManager.add_WalletToDb(walletInfo);
//        DataManager.setUserInfo(walletInfo);
//        UserUtils.setCurrentUserAddress(walletInfo.getAddress());
//
////        syncUserPresenter.syncUser(walletInfo.getAddress());
//        onManageJumpPage();
    }

    @Override
    public void setAccountData(WalletInfo data) {

    }


    @Override
    public void setImportData(WalletInfo data) {
        //type2
        data.setCiphertext(walletInfo.getCiphertext());
        data.setUserName(walletInfo.getUserName());
        data.setSaftyCode(walletInfo.getSaftyCode() + AESCrypt.SerectAppend);

        try {
            String privateKeyAES = AESCrypt.encrypt(data.getSaftyCode(), walletInfo.getCompressedPrivkey());
            data.setCompressedPrivkey(privateKeyAES);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        DataBaseManager.add_WalletToDb(data);
        DataManager.setUserInfo(data);
        UserUtils.setCurrentUserAddress(data.getAddress());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                showLoading(getResources().getString(R.string.loading_sync));
                syncUserPresenter.syncUser(data.getAddress());
            }
        });

    }


    @Override
    public void setWalletData(WalletInfo data) {
        //type 3;
        data.setCiphertext(walletInfo.getCiphertext());
        LogUtil.error("wallet", "3: " + walletInfo.toString());

        DataBaseManager.add_WalletToDb(data);

        if (UserUtils.setCurrentUserAddress(data.getAddress())) {
            LogUtil.error("ramon", "保存address成功");
            DataManager.setUserInfo(data);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                showLoading(getResources().getString(R.string.loading_sync));
                syncUserPresenter.syncUser(data.getAddress());
            }
        });
    }

    @Override
    public void setSyncData(boolean success, int code) {

    }

    private void relogin() {
        MainActivity.reLogin(this);
    }

    @Override
    public void setCountryCodeData(List<CountryCode> data) {

    }

    @Override
    public void setPhoneCodeData(String data) {

    }

    @Override
    public void setSyncPhoneCodeData(String data) {

    }

    @Override
    public void setFailure() {

    }

    @OnClick({R.id.bt_verify})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_verify:
                verifyState();
                break;
        }
    }

    @Override
    public void onSync() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                relogin();
            }
        });
    }

    @Override
    public void onSyncFail(Object obj) {
        dismissLoading();
        toast("同步失败,请重试");
    }
}
